/*Author:no-bald-chen
* Time:2020/9/1
* */
package DataStructure.linkedlist;


//带头结点的单向循环链表
public class CircularLinkedList implements LinkedList{
    private ListNode head;
    private int length;

    public CircularLinkedList() {
        head = new ListNode();
        head.next = head;
        length=0;
    }

    @Override
    public ListNode getHead() {
        return head;
    }

    @Override
    public int getLength() {
        return length;
    }

    //链表初始化
    @Override
    public ListNode initLinkedList(int[] val) {
        if (val==null){
            return null;
        }
        length = val.length;
        ListNode last = head;
        for (int i : val) {
            ListNode node = new ListNode(i);
            node.next = head;
            last.next = node;
            last = node;
        }
        return head;
    }

    @Override
    public void addLast(ListNode node) {
        insertListNode(node,length);
    }

    @Override
    public void addHead(ListNode node) {
        insertListNode(node,0);
    }

    @Override
    public boolean insertListNode(ListNode node, int k) {
        if (k<0 ||k>length){
            return false;
        }
        ListNode temp = head;
        for (int i = 0; i < k; i++) {
            temp = temp.next;
        }
        node.next = temp.next;
        temp.next = node;
        length++;
        return true;
    }

    @Override
    public boolean deleteListNode(int k) {
        if (k<=0 || k>length){
            return false;
        }
        ListNode pre = null;
        ListNode node = head;
        for (int i = 0; i < k; i++) {
            pre =node;
            node = node.next;
        }
        pre.next = node.next;
        node.next = null;
        length--;
        return true;
    }

    @Override
    public ListNode inquireListNode(int k) {
        if (k<=0 || k>length){
            return null;
        }
        ListNode node = head;
        for (int i = 0; i < k; i++) {
            node = node.next;
        }
        return node;
    }

    @Override
    public void travelLinkedList() {
        System.out.println("链表长度为:"+length);
        ListNode node = head;
        while (node.next!=head){
            node = node.next;
            System.out.print(node.val+" ");
        }
        System.out.println();
    }
}
